package com.wangsd.web.coupon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wangsd.common.utils.DateUtils;
import com.wangsd.web.coupon.entity.*;
import com.wangsd.web.coupon.mapper.SignDetailMapper;
import com.wangsd.web.coupon.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author generator
 * @since 2019-10-15
 */
@Slf4j
@Service
public class SignDetailServiceImpl extends ServiceImpl<SignDetailMapper, SignDetail> implements SignDetailService {

    @Resource
    SignDetailMapper signDetailMapper;
    @Autowired
    MemberService memberService;
    @Autowired
    SignConfigService signConfigService;
    @Autowired
    IntegralDetailService integralDetailService;

    @Override
    public Integer sign(String openId) {
        Integer currentPoint;
        Member oldMember = memberService.selectByOpenid(openId);
        SignConfig signConfig = signConfigService.selectByCompanyId(oldMember.getCompanyId());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SignDetail signDetail = this.selectSignLast(openId);
        String nowDate = simpleDateFormat.format(new Date());
        if (signConfig==null||signConfig.getDefaultPoint() == null) {
            return -2;
        }
        /*第一次签到*/
        currentPoint = signConfig.getDefaultPoint();
        if (signDetail == null) {
            /*设置默认积分*/
            this.savePoints(currentPoint, openId, oldMember, 0);
            /*保存当前签到明细*/
            this.saveSignDate(openId, simpleDateFormat, nowDate);
            return currentPoint;
        }

        String lastDate = simpleDateFormat.format(signDetail.getSignDate());
        String specifiedDayBefore = DateUtils.getSpecifiedDayBefore(nowDate);

        /*如果数据库中最后一次签到的时间和当前时间相等，就不允许在签到*/
        if (nowDate.equals(lastDate)) {
            return -1;
        }

        List<SignConfigDetail> signConfigDetails = signConfigService.selectDetailByCompanyId(oldMember.getCompanyId());
        /*
            判断当前时间的前一天是否和上次签到时间一致，如果一致就表示是连续签到，连续签到就将会员表中的积分进行累加；
            签到一次就送10积分，连续签到3天送50,7天150,21天500;
            非连续签到，就将会员表中的连续签到次数改成1，只送10积分
        * */
        if (specifiedDayBefore.equals(lastDate)) {
            /*是连续的日期*/
            /*出现特殊日期积分改变*/
            if (signConfigDetails == null || signConfigDetails.size() < 0) {
                currentPoint = 10;
            } else {
                for (SignConfigDetail signConfigDetail : signConfigDetails) {
                    if ((signConfigDetail.getDay().intValue() - 1) == oldMember.getContinueDay().intValue()) {
                        currentPoint = signConfigDetail.getPoints();
                    }
                }
            }
            this.savePoints(currentPoint, openId, oldMember, 1);
            /*保存当前签到明细*/
            this.saveSignDate(openId, simpleDateFormat, nowDate);
        } else {
            /*不连续*/
            /*会员表中累加积分数据*/
            currentPoint = 10;
            this.savePoints(currentPoint, openId, oldMember, 0);
            /*保存当前签到明细*/
            this.saveSignDate(openId, simpleDateFormat, nowDate);
        }

        /*签到完成之后，向积分明细表中添加积分明细数据*/
        IntegralDetail integralDetail = new IntegralDetail();
        integralDetail.setCreatedTime(new Date());
        integralDetail.setOpenId(openId);
        /*加积分*/
        integralDetail.setStatus(1);
        integralDetail.setIntegral(currentPoint);
        integralDetail.setType(0);
        integralDetail.setRemark("签到积分");
        integralDetailService.save(integralDetail);
        return currentPoint;
    }

    @Override
    public List<SignDetail> selectListByOpenid(String openId) {
        QueryWrapper<SignDetail> query = new QueryWrapper();
        query.eq("open_id", openId);
        List<SignDetail> list = signDetailMapper.selectList(query);
        return list;
    }

    private SignDetail selectSignLast(String openid) {
        QueryWrapper<SignDetail> query = new QueryWrapper();
        query.eq("open_id", openid);
        query.orderByDesc("sign_date");
        List<SignDetail> list = signDetailMapper.selectList(query);
        SignDetail signDetail = null;
        if (list != null && list.size() > 0) {
            signDetail = list.get(0);
        }
        return signDetail;
    }

    /*保存积分*/
    private void savePoints(Integer points, String openId, Member oldMember, Integer state) {
        Member member = new Member();
        member.setMiniOpenid(openId);
        if (state == 0) {
            /*非连续签到，重置为1*/
            member.setContinueDay(1);
        } else {
            /*连续签到，累加*/
            member.setContinueDay(oldMember.getContinueDay() + 1);
        }
        member.setIntegral(points + oldMember.getIntegral());
        memberService.register(member);
    }

    /*保存详细签到日期*/
    private void saveSignDate(String openId, SimpleDateFormat simpleDateFormat, String nowDate) {
        SignDetail signDetailNotContinue = new SignDetail();
        signDetailNotContinue.setOpenId(openId);
        Date parse;
        try {
            parse = simpleDateFormat.parse(nowDate);
            signDetailNotContinue.setSignDate(parse);
        } catch (Exception e) {
            log.info("日期转换异常", e);
        }
        signDetailMapper.insert(signDetailNotContinue);
    }
}
